package com.zxjbyte.yiyi.module.plugin.socket.api;

import com.zxjbyte.yiyi.framework.common.domain.message.StreamMessage;
import com.zxjbyte.yiyi.module.plugin.socket.manager.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @Author zhangxingjia
 * @Date 2024/7/15 18:38
 * @Version: 1.0
 */
@Slf4j
@Service
public class WebSocketApiImpl implements WebSocketApi{

    @Override
    public boolean sendTextMessage(String userId, String message) {
        WebSocketSession session = WebSocketSessionManager.getSession(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean sendOneMessage(String userId, StreamMessage message) {
        return WebSocketSessionManager.sendMessage(userId, message);
    }

    @Override
    public void broadcastMessage(StreamMessage message) {
        WebSocketSessionManager.broadcastMessage(message);
    }

    @Override
    public int getOnlineCount() {
        return WebSocketSessionManager.getOnlineCount();
    }
}
